<?php

namespace App\Service\OpenShop;

use App\Models\Common\ConfigModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Remote\Feishu\Departments\DepartmentsRemote;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\FeishuApiService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class ContractTemplateFeiShuService extends BaseService
{

    // 对应飞书callback返回的 approval_code 参数值
    const FEI_SHU_APPROVAL_CODE_CONTRACT_TEMPLATE = 'F3329F7C-B77E-4747-9898-21AB5B7EB5F1'; // 加盟政策

    // 对应飞书返回的表单id
    const FORM_DATA_ID_NAME                                 = "widget17010727286040001"; // 政策名称
    const FORM_DATA_ID_TIME_START_END                       = "widget17010727428060001"; // 起始时间
    const FORM_DATA_ID_CONTRACT_TYPE                        = 'widget17010729311520001'; // 签约类型
    const FORM_DATA_ID_SHOP_COUNT                           = 'widget17010755669510001'; // 门店数量
    const FORM_DATA_ID_MODE                                 = 'widget17010728590210001'; // 加盟模式
    const FORM_DATA_ID_DEPOSIT                              = 'widget17010731068150001'; // 保证金
    const FORM_DATA_ID_DEPOSIT_AMOUNT                       = 'widget17010731071510001'; // 定金模式： 定金金额
    const FORM_DATA_ID_INITIAL_FEE                          = 'widget17010730458360001'; // 传统模式：  品牌使用费 (元) == 加盟费
    const FORM_DATA_ID_TECHNOLOGY_TRANSFER_FEE              = 'widget17010730464380001'; // 传统模式： 经营技术授予费(元) == 技术转让费
    const FORM_DATA_ID_GUIDANCE_FEE                         = 'widget17010730466270001'; // 传统模式：咨询指导服务费==品牌指导费
    const FORM_DATA_ID_MANAGEMENT_COST                      = 'widget17010730468020001'; // 传统模式：特权使用费(管理费)第一年(元)
    const FORM_DATA_ID_MANAGEMENT_COST_EVERY_YEAR           = 'widget17010731066330001'; // 传统模式：特权使用费(管理费)每年(元)
    const FORM_DATA_ID_DECORATION_DEPOSIT                   = 'widget17010731069820001'; // 传统模式：装修保证金
    const FORM_DATA_ID_DEPOSIT_AMOUNT_RATIO                 = 'widget17010743187860001'; // 分账模式：每月实收抽佣比例
    const FORM_DATA_ID_MONTH_REAL_AMOUNT_COMMISSION_CAPPING = 'widget17010743564750001'; // 分账模式：月实收抽佣封顶金额
    const FORM_DATA_ID_AMOUNT_COMMISSION_CAPPING            = 'widget17010784223300001'; // 分账模式：抽佣累计封顶金额


    /**
     * @throws GuzzleException
     */
    public static function getInstancesIdData(string $appId, string $instancesId)
    {

        try {
            $appInfo      = ConfigModel::getFsConfigByAppId($appId);
            $appletConfig = [
                "platformName" => $appInfo['platformName'],
                'appId'        => $appInfo['appId'],
                'appSecret'    => $appInfo['appSecret'],
                'ext'          => 604800,
                'inv'          => 604800
            ];
            $token        = FeishuApiService::accessToken($appletConfig);
            $res          = DepartmentsRemote::getInstanceInfo($instancesId, $token);

            Log::info("contract_template_fei_shu_data", ['data' => $res]);

            return $res;
        } catch (Exception $e) {
            Log::info("contract_template_fei_shu_getInstancesIdData_error", ['data' => $e]);
            return [];
        }

    }


    /**
     * 飞书卡片消息内容处理
     * @param array $data
     * @param array $cardData
     * @return array
     */
    public static function dealFeiShuCardMsgContent(array $data, array $cardData): array
    {
        // 推送卡片消息
        $card = [
            "header"   => [
                "title" => [
                    "tag"     => "plain_text",
                    "content" => '新的加盟政策已创建启用'
                ]
            ],
            'elements' => [
                [
                    "tag"     => "markdown",
                    "content" => "政策名称：" . $data['templateName']
                ],
                [
                    "tag"     => "markdown",
                    "content" => "开始时间：" . date("Y-m-d", $data['startTime'])
                ],
                [
                    "tag"     => "markdown",
                    "content" => "结束时间：" . date("Y-m-d", $data['endTime'])
                ],
                [
                    "tag"     => "markdown",
                    "content" => "签约类型：" . implode(",", $cardData['fsCardContractTypeStr']) ?? ""
                ],
                [
                    "tag"     => "markdown",
                    "content" => "签约门店数量（家）：" . $data['shopCount']
                ],
                [
                    "tag"     => "markdown",
                    "content" => "加盟模式：" . OpenShopContractTemplateModel::MODE_MAP_TEXT[$data['mode']]
                ],
                [
                    "tag"     => "markdown",
                    "content" => "保证金（元）：" . $data['deposit'] / 100
                ]

            ],

        ];

        switch ($data['mode']) {
            case OpenShopContractTemplateModel::MODE_1:
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "品牌使用费（元）：" . $data['initialFee'] / 100
                    ];
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "经营技术授予费（元）：" . $data['technologyTransferFee'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "咨询指导服务费（元）：" . $data['guidanceFee'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "特权使用费第一年（元）：" . $data['managementCost'] / 100
                    ];
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "特权使用费每年（元）：" . $data['managementCostEveryYear'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "装修保证金（元）：" . $data['decorationDeposit'] / 100
                    ];

                break;

            case  OpenShopContractTemplateModel::MODE_2:

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "每月实收抽佣比例：" . $cardData['fsCardDepositAmountRatio']
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "月实收抽佣封顶金额（元）：" . $data['monthRealAmountCommissionCapping'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "抽佣累计封顶金额（元）：" . $data['amountCommissionCapping'] / 100
                    ];

                break;

            case  OpenShopContractTemplateModel::MODE_3:

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "品牌使用费（元）：" . $data['initialFee'] / 100
                    ];
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "经营技术授予费（元）：" . $data['technologyTransferFee'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "咨询指导服务费（元）：" . $data['guidanceFee'] / 100
                    ];

                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "特权使用费第一年（元）：" . $data['managementCost'] / 100
                    ];
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "特权使用费每年（元）：" . $data['managementCostEveryYear'] / 100
                    ];
                $card['elements'][] =
                    [
                        "tag"     => "markdown",
                        "content" => "定金金额（元）：" . $data['depositAmount'] / 100
                    ];
                break;

        }

        return $card;

    }


}